package com.ygqh.baby.controller.mobile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.BalanceType;
import com.ygqh.baby.ao.CommissionStatus;
import com.ygqh.baby.ao.FileType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.OperationType;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.ao.UserType;
import com.ygqh.baby.model.YgCommissionModel;
import com.ygqh.baby.model.YgCompanyBalanceCollectModel;
import com.ygqh.baby.model.YgUserBalanceDetailModel;
import com.ygqh.baby.model.YgUserBalanceOrderInfo;
import com.ygqh.baby.model.YgUserCultivationDayModel;
import com.ygqh.baby.model.YgUserShareOrderModel;
import com.ygqh.baby.po.YgAgentInviteRecord;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserBalance;
import com.ygqh.baby.po.YgUserBank;
import com.ygqh.baby.po.YgUserCultivationDay;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.YgAgentInviteRecordService;
import com.ygqh.baby.service.YgCommissionService;
import com.ygqh.baby.service.YgUserBalanceService;
import com.ygqh.baby.service.YgUserCultivationDayService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.QRCodeUtil;
import com.ygqh.baby.utils.SessionUtil;

/**
 * 我的返利
 * 
 * @author guohao
 *
 */
@Controller
@RequestMapping("/mobile/rebate")
public class YgMyRebateController extends BaseController {

	@Autowired
	private YgUserBalanceService ygUserBalanceService;
	@Autowired
	private YgCommissionService ygCommissionService;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private FileService fileService;
	@Value("${promotion.link}")
	protected String promotionLink;
	@Autowired
	private DocumentConstant documentConstant;
	@Autowired
	private YgCommissionService commissionService;
	@Autowired
	private YgUserService userService;
	@Autowired
	private YgUserCultivationDayService ygUserCultivationDayService;
	@Autowired
	private YgAgentInviteRecordService ygAgentInviteRecordService;

	@RequestMapping("findMyRebate")
	@ResponseBody
	public JSONPObject getMyRebate(String callback) {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();

		Map<String, Object> map = new HashMap<String, Object>();
		YgUserBalance balance = ygUserBalanceService.findByUserId(user.getId());
		int count = 0;
		if (UserType.Group.equals(user.getUserType())) {
			count = userService.findUserRecommendCount(null, user.getGroupTag());
		} else{
			count = userService.findUserRecommendCount(user.getSourceCode(), null);
		}
		map.put("preincomePrice", balance.getPreincomePrice());
		map.put("balancePrice", balance.getBalancePrice());
		map.put("withdrawPrice", balance.getWithdrawPrice());
		map.put("userRecommendCount", count);
		map.putAll(ygUserBalanceService.getUserShareOrderPrice(user.getId()));
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}

	/**
	 * 预收入详细列表
	 * 
	 * @param queryInfo
	 * @param callback
	 * @return
	 */
	@RequestMapping("findBalanceDetails")
	@ResponseBody
	public JSONPObject findBalanceDetails(QueryInfo queryInfo, String callback) {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserBalanceDetailModel> list = ygUserBalanceService.findBalanceDetailsByType(queryInfo, user.getId(), null, "PreIncome");
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, list));
		return json;
	}

	@RequestMapping("findShareOrderInfo")
	@ResponseBody
	public JSONPObject findShareOrderInfo(Long orderId, String callback) {
		JSONPObject json = null;
		YgUserShareOrderModel model = ygUserBalanceService.findShareOrderInfo(orderId);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));
		return json;
	}

	@RequestMapping("findOrderList")
	@ResponseBody
	public JSONPObject findOrderList(QueryInfo queryInfo, String callback) {
		JSONPObject json;
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserShareOrderModel> model = ygUserBalanceService.getUserShareOrder(queryInfo, user);
		// List<YgUserBalanceOrderModel> model =
		// ygUserBalanceService.findOrderList(queryInfo, user.getSourceCode());
//		ygUserCultivationDayService.findByDay(startDate, endDate);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));
		return json;
	}

	@RequestMapping("findOrderBalanceDetail")
	@ResponseBody
	public JSONPObject findOrderBalanceDetail(String ubdOrderId, OperationType operationType, BalanceType balanceType, Long userId, String callback) {
		JSONPObject json = null;
		Long uid;
		if (userId != null) {
			uid = userId;
		} else {
			YgUser user = SessionUtil.getCurrentUser();
			uid = user.getId();
		}
		YgUserBalanceOrderInfo model = ygUserBalanceService.findOrderBalanceDetailV2(ubdOrderId, balanceType, operationType, uid);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));
		return json;
	}

	@RequestMapping("bindBank")
	@ResponseBody
	public JSONPObject bindBank(Long bankId, String bankAccount, String alipayCode, String callback) {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		int row = ygCommissionService.bindBank(user.getId(), bankId, bankAccount, "", "", "", alipayCode);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, row));
		return json;
	}

	@RequestMapping("findBankInfo")
	@ResponseBody
	public JSONPObject findBankInfo(String callback) {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		YgUserBank bank = ygCommissionService.findBankInfo(user.getId());
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, bank));
		return json;
	}

	/**
	 * 申请提现
	 * 
	 * @param commissionPrice
	 * @param callback
	 * @return
	 */
	@RequestMapping("applyWithdrawals")
	@ResponseBody
	public JSONPObject applyWithdrawals(BigDecimal commissionPrice, String callback) {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		int row = ygCommissionService.applyWithdrawals(user.getId(), user.getUserName(), commissionPrice);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, row));
		return json;
	}

	@SuppressWarnings("deprecation")
	@RequestMapping("getQRCodeUrl")
	@ResponseBody
	public JSONPObject getPRCodeUrl(String callback, HttpServletRequest request) throws UnsupportedEncodingException {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		String url = promotionLink + "?sourceCode=" + user.getSourceCode();
		String path = request.getRealPath("/");
		String realPath = path + "/QrCodeImage";
		String fileName = "qr" + user.getSourceCode() + ".jpg";
		String qrcodeUrl = "";
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			File file = QRCodeUtil.getFile(url, realPath, fileName);
			if (!StringUtil.isBlank(realPath)) {
				String ext = fileName.split("\\.")[1];
				qrcodeUrl = fileService.uploadImage(file, new FileType[] { FileType.QrCode }, ext, true, request);

			}
		} catch (Exception e) {
			logger.debug("生成推广二维码失败.sourceCode = " + user.getSourceCode());
			e.printStackTrace();
		}
		// 生成推广短连接
		String shortUrl = wxMpAuthorityService.getShortUrl(url);
		map.put("codeUrl", qrcodeUrl);
		map.put("promotionLink", shortUrl);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}

	/**
	 * 查找可提现金额列表
	 * 
	 * @param queryInfo
	 * @param callback
	 * @return
	 */
	@RequestMapping("findWithdrawableMoney")
	@ResponseBody
	public JSONPObject findWithdrawableMoney(QueryInfo queryInfo, String callback) {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		// List<YgUserBalanceDetailModel> sourceList =
		// ygUserBalanceService.findBalanceDetailsByType(queryInfo,
		// user.getId(), "Balance", null);
		// List<YgUserBalanceDetailModel> outList = sourceList.stream().filter(e
		// -> e.getBalancePrice().doubleValue() > 0)
		// .filter(e ->
		// e.getOperation().equals("新增")).collect(Collectors.toList());
		// List<YgUserBalanceDetailModel> inList = sourceList.stream().filter(e
		// -> e.getBalancePrice().doubleValue() < 0)
		// .filter(e ->
		// e.getOperation().equals("退货")).collect(Collectors.toList());
		// List<YgUserBalanceDetailModel> newList = new ArrayList<>();
		// outList.forEach(out -> {
		// inList.forEach(in -> {
		// if (out.getOrderId().equals(in.getOrderId())) {
		// out.setBalancePrice(out.getBalancePrice().add(in.getBalancePrice()));
		// }
		// });
		// newList.add(out);
		// });
		// List<YgUserBalanceDetailModel> otherList =
		// sourceList.stream().filter(e -> e.getOperation().equals("提现失败返还") ||
		// e.getOperation().equals("申请提现"))
		// .collect(Collectors.toList());
		//
		// List<YgUserBalanceDetailModel> resultList = newList.stream().filter(e
		// -> e.getBalancePrice().doubleValue() >
		// 0).collect(Collectors.toList());
		// resultList.addAll(otherList);
		// resultList = resultList.stream().sorted((p2, p1) ->
		// p1.getCreateTime().compareTo(p2.getCreateTime())).collect(Collectors.toList());
		List<YgUserBalanceDetailModel> list = ygUserBalanceService.findBalanceDetailsByType(queryInfo, user.getId(), "balance", null);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, list));
		return json;
	}

	/**
	 * 查找提现记录
	 * 
	 * @param queryInfo
	 * @param callback
	 * @return
	 */
	@RequestMapping("findWithdrawMoneyRecord")
	@ResponseBody
	public JSONPObject findWithdrawMoneyRecord(QueryInfo queryInfo, String callback) {
		JSONPObject json;
		YgUser user = SessionUtil.getCurrentUser();

		ResultSet<YgCommissionModel> resultSet = commissionService.searchModel(queryInfo, user.getId(), null);
		json = new JSONPObject(callback, Message.success(resultSet.toDatatables(null)));
		return json;
	}

	/**
	 * 查找已提现金额
	 * 
	 * @param queryInfo
	 * @param callback
	 * @return
	 */
	@RequestMapping("findWithdrewMoney")
	@ResponseBody
	public JSONPObject findWithdrewMoney(QueryInfo queryInfo, String callback) {
		JSONPObject json;
		YgUser user = SessionUtil.getCurrentUser();
		ResultSet<YgCommissionModel> resultSet = commissionService.searchModel(queryInfo, user.getId(),
				new String[] { CommissionStatus.PaySuccess.name(), CommissionStatus.WaitingPay.name() });
		json = new JSONPObject(callback, Message.success(resultSet.getResult()));
		return json;
	}

	/**
	 * 提现
	 * 
	 * @return
	 */
	@RequestMapping("withdraw")
	@ResponseBody
	public JSONPObject withdraw(String callback, BigDecimal money) {

		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		Message message = null;
		try {
			message = commissionService.withdraw(user, money);
		} catch (Exception e) {
			Message.error("提现失败", e.getMessage());
			e.printStackTrace();
		}
		json = new JSONPObject(callback, message);
		return json;
	}

	/**
	 * 提现进度
	 * 
	 * @return
	 */
	@RequestMapping("findRateOfProgress")
	@ResponseBody
	public JSONPObject findRateOfProgress(String callback, Long commissionId) {
		JSONPObject json;
		json = new JSONPObject(callback, Message.success(commissionService.findModelById(commissionId)));
		return json;
	}

	/**
	 * 查找企业用户预收入明细
	 * 
	 * @return
	 */
	@RequestMapping("findCompanyPreIncomeList")
	@ResponseBody
	public JSONPObject findCompanyPreIncomeList(QueryInfo queryInfo, String callback) {
		JSONPObject json;
		YgUser user = SessionUtil.getCurrentUser();
		ResultSet resultList = ygUserBalanceService.findCompanyPreIncomeList(queryInfo, user.getId());
		json = new JSONPObject(callback, Message.success(resultList));
		return json;
	}

	/**
	 * 查找企业用户累计返利明细
	 * 
	 * @return
	 */
	@RequestMapping("findCompanyBalanceList")
	@ResponseBody
	public JSONPObject findCompanyBalanceList(QueryInfo queryInfo, String callback) {
		JSONPObject json;
		YgUser user = SessionUtil.getCurrentUser();
		ResultSet resultList = ygUserBalanceService.findCompanyBalanceList(queryInfo, user.getId());
		json = new JSONPObject(callback, Message.success(resultList));
		return json;
	}

	/**
	 * 查找企业用户预收入明细-通过用户id
	 * 
	 * @return
	 */
	@RequestMapping("findCompanyPreIncomeListByUserId")
	@ResponseBody
	public JSONPObject findCompanyPreIncomeListByUserId(QueryInfo queryInfo, String callback, Long userId) {
		JSONPObject json;
		ResultSet resultList = ygUserBalanceService.findCompanyPreIncomeListByUserId(queryInfo, userId, BalanceType.PreIncome);
		json = new JSONPObject(callback, Message.success(resultList));
		return json;
	}

	/**
	 * 查找企业用户累计返利明细-通过用户id
	 * 
	 * @return
	 */
	@RequestMapping("findCompanyBalanceListByUserId")
	@ResponseBody
	public JSONPObject findCompanyBalanceListByUserId(QueryInfo queryInfo, String callback, Long userId) {
		JSONPObject json;
		ResultSet resultList = ygUserBalanceService.findCompanyPreIncomeListByUserId(queryInfo, userId, BalanceType.Balance);
		json = new JSONPObject(callback, Message.success(resultList));
		return json;
	}

	/**
	 * 企业预收入返利，按员工聚合查询
	 * 
	 * @return
	 */
	@RequestMapping("findPreIncomeCompanyMoneyCollectByUser")
	@ResponseBody
	public JSONPObject findPreIncomeCompanyMoneyCollectByUser(String callback) {
		JSONPObject json;
		YgUser user = SessionUtil.getCurrentUser();
		List<YgCompanyBalanceCollectModel> resultList = ygUserBalanceService.findPreIncomeCompanyMoneyCollectByUser(user.getId());
		if (resultList.isEmpty())
			return new JSONPObject(callback, Message.success(null));
		BigDecimal sum = resultList.stream().map(m -> m.getTotalMoney()).reduce(new BigDecimal(0), (a, b) -> (a.add(b)));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", resultList);
		map.put("sum", sum);
		json = new JSONPObject(callback, Message.success(map));
		return json;
	}

	/**
	 * 企业累计收入返利，按员工聚合查询
	 * 
	 * @return
	 */
	@RequestMapping("findBalanceCompanyMoneyCollectByUser")
	@ResponseBody
	public JSONPObject findBalanceCompanyMoneyCollectByUser(String callback) {
		JSONPObject json;
		YgUser user = SessionUtil.getCurrentUser();
		List<YgCompanyBalanceCollectModel> resultList = ygUserBalanceService.findBalanceCompanyMoneyCollectByUser(user.getId());
		BigDecimal sum = resultList.stream().map(m -> m.getTotalMoney()).reduce(new BigDecimal(0), (a, b) -> (a.add(b)));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", resultList);
		map.put("sum", sum);
		json = new JSONPObject(callback, Message.success(map));
		return json;
	}

	/**
	 * 预收入总和AND累计收入总和
	 * 
	 * @return
	 */
	@RequestMapping("findCompaneyPreIncomeAndBalanceSum")
	@ResponseBody
	public JSONPObject findCompaneyPreIncomeAndBalanceSum(String callback) {
		JSONPObject json;
		YgUser user = SessionUtil.getCurrentUser();
		Map<String, Object> resultMap = ygUserBalanceService.findCompaneyPreIncomeAndBalanceSum(user.getId());
		json = new JSONPObject(callback, Message.success(resultMap));
		return json;
	}

	/**
	 * 代理用户耕耘成果
	 * 
	 * @param queryInfo
	 * @param orderStatus
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "getUserCultivation", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findUserCultivation(String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserCultivationDayModel> userCultivation = ygUserCultivationDayService.queryUserCultivationGroupByUserId(user.getId());
		List<YgUserCultivationDayModel> userCultList = new ArrayList<YgUserCultivationDayModel>();
		
		String today = DateConvertUtils.format(new Date());
		YgAgentInviteRecord agentInviteRecord = ygAgentInviteRecordService.findValidByReceiveUserId(user.getId());
		if (agentInviteRecord == null || agentInviteRecord.getCancelTime() != null) {
			return new JSONPObject(callback, Message.success(userCultList));
		}
		String startDate = DateConvertUtils.format(DateConvertUtils.addMonth(agentInviteRecord.getReceiveTime(), -1), "yyyy-MM-dd");
		List<String> months = DateConvertUtils.diffMonth(startDate, today);

		for (String mon : months) {
			boolean blag = true;
			for (YgUserCultivationDayModel userCult : userCultivation) {
				if (mon.equals(userCult.getMonth())) {
					blag = false;
					userCultList.add(userCult);
					break;
				}
			}
			if (blag) {
				YgUserCultivationDayModel userCult = new YgUserCultivationDayModel();
				userCult.setMonth(mon);
				userCult.setTotalPrice(new BigDecimal(0.00));
				userCultList.add(userCult);
			}
		}
		Collections.sort(userCultList, (o1, o2) -> {
			Date date1 = DateConvertUtils.parse(o1.getMonth(), "yyyy-MM");
			Date date2 = DateConvertUtils.parse(o2.getMonth(), "yyyy-MM");
			return date2.compareTo(date1);
		});
		JSONPObject json = new JSONPObject(callback, Message.success(userCultList));
		return json;
	}

	/**
	 * 按月查询耕耘成果明细
	 * @param date		年月 例：2018-05-01
	 * @param callback
	 * @return
	 */
	@RequestMapping("findOrderListByMonth")
	@ResponseBody
	public JSONPObject findOrderListByMonth(Date month, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		if (month == null) { // 默认当月
			month = new Date();
		}
		Date startDate = DateConvertUtils.getMonthStartDate(month);
		Date endDate = DateConvertUtils.getMonthEndDate(month);
		List<YgUserCultivationDay> list = ygUserCultivationDayService.findByUserIdAndDay(startDate,
				endDate, user.getId());
		BigDecimal totalPriceByMonth = new BigDecimal("0.00");
		if (CollectionUtils.isNotEmpty(list)) {
			totalPriceByMonth = list.stream().map(o -> o.getTotalPrice()).reduce((p1, p2) -> p1.add(p2)).get();
		}
		Map<String, Object> data = new HashMap<>();
		data.put("totalPriceByMonth", totalPriceByMonth);
		data.put("userCultivationList", list);
		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, data));
	}

}
